﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyBBS.Services;
using System.Web.Security;
using MyBBS.Controllers.ViewData;

namespace MyBBS.Controllers
{
    public class UserController : BaseController
    {

        public UserController(IUserService userService) : base(userService)
        {
            
        }

        public ActionResult Index()
        {
            // Add action logic here
            throw new NotImplementedException();
        }

        public ActionResult SignUp(string userName, string password, string email)
        {
            Result result = new Result();
            try
            {
                MembershipCreateStatus status =  _userService.SignUp(userName, password, email);
                if (status == MembershipCreateStatus.Success)
                {
                    result.isSuccessful = true;
                    result.errorMessage = "Welcome back, " + userName + " !";
                }
                else
                {
                    result.isSuccessful = false;
                    result.errorMessage = status.ToString();
                }

            }
            catch(Exception)
            {
                result.isSuccessful = false;
                result.isException = true;
                result.errorMessage = "Sorry, We encounter a problem of signing up. Please try later!";
            }

            return View("Json", result);
        }

        public ActionResult Login(string userName, string password)
        {                   
            Result result = new Result();
            try
            {
                if (_userService.Login(userName, password))
                {
                    result.isSuccessful = true;
                }
                else
                {
                    result.isSuccessful = false;
                    result.errorMessage = "Wrong username or password!";
                }
            }
            catch
            {
                result.isSuccessful = false;
                result.isException = true;
                result.errorMessage = "System error";
            }

            return View("Json", result);
        }

        public ActionResult Logout()
        {
            Result result = new Result();
            if (_userService.Logout())
            {
                result.isSuccessful = true;
            }
            else
            {
                result.errorMessage = "Sorry, logout error";
                result.isSuccessful = false;
            }

            return View("Json", result);
        }
    }
}
